package com.fs.controller.general;

import com.fs.controller.PicFitUtil;
import com.fs.controller.vo.PageData;
import com.fs.controller.vo.shop.ReqShopQuery;
import com.fs.controller.vo.shop.RespShop;
import com.fs.controller.vo.shop.RespShopWithOnePic;
import com.fs.global.config.CustomConfig;
import com.fs.global.init.RoleName;
import com.fs.service.ShopService;
import com.fs.service.bo.BoPageInfo;
import com.fs.service.bo.shop.BoShop;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Api(tags = "门店API(共用)", description = "管理员和小程序用户公用")
@RestController
@RequestMapping(path = {"/v2/shop", "/v1/shop"})
@RequiresRoles(value = {RoleName.GUEST, RoleName.CUSTOMER, RoleName.ADMIN}, logical = Logical.OR)
@Validated
public class ShopPublicController {

    private final ShopService shopService;
    private final PicFitUtil picFitUtil;
    private final CustomConfig config;

    public ShopPublicController(ShopService shopService, PicFitUtil picFitUtil, CustomConfig config) {
        this.shopService = shopService;
        this.picFitUtil = picFitUtil;
        this.config = config;
    }

    @ApiOperation("获取门店列表")
    @GetMapping
    public PageData<RespShopWithOnePic> getShops(ReqShopQuery query) {
        BoPageInfo<BoShop> pageInfo = shopService.getShopByPage(query.getName(), query.getPageNo(), query.getPageSize());

        List<RespShopWithOnePic> shops = pageInfo.getResults().stream().map(shop -> {
            String imageDir = picFitUtil.getAbsImageDirOfShop(shop.getId());
            File dir = new File(imageDir);
            if (!dir.exists()) {
                return new RespShopWithOnePic(shop, "");
            }
            String[] pics = dir.list();
            if (pics == null || pics.length == 0) {
                return new RespShopWithOnePic(shop, "");
            }
            String relPath = picFitUtil.getRelImagePathOfShop(pics[0], shop.getId());
            String picUrl = String.format("http://%s/display?path=%s&op=thumbnail&w=100&h=100", config.getPicfitAddress(), relPath);
            return new RespShopWithOnePic(shop, picUrl);

        }).collect(Collectors.toList());
        return new PageData<>(shops, pageInfo.getTotal());

    }
}
